var express = require('express');
var router = express.Router();
const jwt = require("jsonwebtoken");
const multiparty = require('multiparty');
const path = require('path');
let { secretKey } = require("../utils")

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get("/getToken", function (req, res, next) {
  //获取请求头中的token
  const token = req.get("Authorization");
  //将token解密
  const data = jwt.verify(token.split(" ")[1], secretKey);
  res.send({
    data
  })
})

router.get('/getFrontToken', function (req, res) {
  // 获取到客户端发送过来的 token
  const token = req.get('Authorization');
  console.log(token);
  // 将编码后的 token 再转换回来
  let decode = { data: { username: "游客" } };
  try {
    decode = jwt.verify(token.split(" ")[1], secretKey);
  } catch (e) {
    let token = jwt.sign(decode, secretKey);
    decode.token = token;
  }
  res.send(decode);
})

// 上传的接口
// 获取二进制数据，保存数据，将上传的文件名重命名，名字要返回去
router.post("/upload", function (req, res) {
  // 将上传的数据存入到images里
  var form = new multiparty.Form({ uploadDir: "./public/image" });
  //  截取改名后的文件名并传回去
  form.parse(req, function (err, fields, files) {
    if (err) {
      res.send(err);
    } else {
      console.log(files.file);
      var p = files.file[0].path.substring(
        files.file[0].path.indexOf("image")
      );
      res.send({ filename: path.basename(p) });
    }
  });
});
module.exports = router;
